﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace SpeedTest
{
	public partial class AdminServer : Form
	{
		Data data = null;
		string recordID = String.Empty;

		public AdminServer(Data data)
		{
			InitializeComponent();
			this.data = data;
		}

		private void AdminServer_Load(object sender, EventArgs e)
		{
			

			cmboDefaultRole.ValueMember = "Value";
			cmboDefaultRole.DisplayMember = "Text";
			LoadRoles();

			LoadSettings();

			EnableInput(false);
		}

		private void LoadSettings()
		{
			DataTable table = data.GetServerSettings();

			if (table != null && table.Rows.Count > 0)
			{
				txtPath.Text = table.Rows[0]["Path"].ToString();

				chkAutoActivate.Checked = Boolean.Parse(table.Rows[0]["AutoActivateUsers"].ToString());

				recordID = table.Rows[0]["ID"].ToString();
			}
		}

		private void FillCombo(DataTable table, int valueIndex, int textIndex, ComboBox combo)
		{
			if (table != null && table.Rows.Count > 0)
			{
				combo.Items.Clear();

				for (int i = 0; i < table.Rows.Count; i++)
				{
					ComboItem ci = new ComboItem();
					ci.Text = table.Rows[i][textIndex].ToString();
					ci.Value = table.Rows[i][valueIndex].ToString();

					combo.Items.Add(ci);
				}
			}
		}

		private void LoadRoles()
		{
			DataTable table = data.GetRoles();
			if (table != null)
			{
				FillCombo(table, table.Columns["ID"].Ordinal, table.Columns["Description"].Ordinal, cmboDefaultRole);
			}
		}

		private void EnableInput(bool enable)
		{
			txtPath.Enabled = enable;
			chkAutoActivate.Enabled = enable;
			cmboDefaultRole.Enabled = enable;

			btnSave.Enabled = enable;
			btnCancel.Enabled = enable;

			if (IsPermitted(btnEdit, data.User.Server)) { btnEdit.Enabled = !enable; }
			else { btnEdit.Enabled = false; }
        }

		private bool IsPermitted(Button btn, Permissions perm)
		{
			if (btn == btnEdit) { return perm.Edit; }

			return false;
		}

		private void btnEdit_Click(object sender, EventArgs e)
		{
			EnableInput(true);
            txtPath.Focus();
		}

		private void btnSave_Click(object sender, EventArgs e)
		{
            if (ValidateChildren())
            {
                DataTable table = new DataTable();
                table.Columns.Add("Path");
                table.Columns.Add("AutoActivateUsers");
                table.Columns.Add("DefaultRole");


                string[] row = new string[3];
                row[0] = txtPath.Text;

                if (chkAutoActivate.Checked) { row[1] = "TRUE"; }
                else { row[1] = "FALSE"; }

                ComboItem ci = (ComboItem)cmboDefaultRole.SelectedItem;
                if (ci != null) { row[2] = ci.Value; }

                table.Rows.Add(row);

                data.UpdateServerSettings(table, recordID);

                DataTable dt = data.GetRoles();

                EnableInput(false);
            }
		}

		private void btnCancel_Click(object sender, EventArgs e)
		{
			EnableInput(false);
		}

        private void cmboDefaultRole_Validating(object sender, CancelEventArgs e)
        {
            ComboBox cb;
            try
            {
               cb = (ComboBox)sender;
            }
            catch (InvalidCastException)
            {
                return;
            }

            if (cb.Text == "")
            {
                //Do not allow blank for the command role field when writing
                e.Cancel = true;
                errorProvider.SetError(cb, "You must select a role.");
            }
        }

        private void cmboDefaultRole_Validated(object sender, EventArgs e)
        {
            Control cb;
            try
            {
                cb = (Control)sender;
            }
            catch (InvalidCastException)
            {
                return;
            }

            errorProvider.SetError(cb, "");
        }

        private void cmboDefaultRole_SelectedIndexChanged(object sender, EventArgs e)
        {
            CancelEventArgs ce = new CancelEventArgs();
            cmboDefaultRole_Validating(sender, ce);
            if (!ce.Cancel)
                cmboDefaultRole_Validated(sender, e);
        }

        private void txtPath_Validating(object sender, CancelEventArgs e)
        {
            TextBox tb;
            try
            {
                tb = (TextBox)sender;
            }
            catch (InvalidCastException)
            {
                return;
            }

            if (!Directory.Exists(tb.Text))
            {
                errorProvider.SetError(tb, "The specified directory does not exist");
                e.Cancel = true;
            }
        }

        private void txtPath_Validated(object sender, EventArgs e)
        {
            TextBox tb;
            try
            {
                tb = (TextBox)sender;
            }
            catch (InvalidCastException)
            {
                return;
            }

            errorProvider.SetError(tb, "");
        }
	}
}
